<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\Address;
use app\Request;
use think\db\exception\DbException;
use think\Response;
use think\response\Json;

class AddressController extends BaseController
{
    protected array $middleware=['Login'=>[
        'except'=>['','',''],
    ]];

    /**
     * 列表
     * @param Request $request
     * @return Json
     */
    public function index(Request $request)
    {

        $rows=Address::where(['users_id'=>$request->users_id])->order(['id'=>'desc'])->paginate()->items();
        writeJson($rows);
    }
	
    /**
     * 新增地址
     * @param Request $request
     * @return Json
     */
    function add(Request $request)
    {
        $AddressModel = new Address();
        $params = $request->param();
        if ($params['default']==1){
            $AddressModel->where(['users_id'=>$request->users_id,'default'=>1])->update(['default'=>0]);
        }
        $AddressModel->save($params);
		
	    writeJson($AddressModel);
    }


    /**
     * 设置默认地址
     * @param int $id
     * @param Request $request
     * @return Json
     */
    function set_default(int $id,Request $request)
    {
        Address::where(['users_id'=>$request->users_id,'default'=>1])->update(['default'=>0]);
        Address::where(['id'=>$id])->update(['default'=>1]);
        writeJson();
    }


    /**
     * 编辑
     * @param Request $request
     * @param int $id
     * @return Json
     */
    public function edit(Request $request,int $id)
    {
        $AddressModel = new Address();
        $row = $AddressModel->find($id);
        if (!$request->isPost()){
            writeJson($row);
        }
        $params = $request->param();
        $row->save($params);
        writeJson($row);
    }

    /**
     * 删除地址
     * @param int $id
     * @return Json
     */
    public function delete(int $id)
    {
        Address::destroy($id);
        writeJson();
    }

    /**
     * 获取默认地址
     * @param Request $request
     * @return Json
     */
    function get_default(Request $request)
    {
        $row = Address::where(['users_id'=>$request->users_id,'default'=>1])->find();
        writeJson($row);
    }
}
